﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;


public class MeshMerger : Editor {

    [MenuItem("Manipulation/Merge selected GameObject")]
    public static void MergeMaterial () {
        GameObject[] selectedObjs = Selection.gameObjects;
        List<CombineInstance> instances = new List<CombineInstance>();
        List<Material> materials = new List<Material>();

        for (int i = 0; i < selectedObjs.Length; i++) {
            GameObject gameObject = selectedObjs[i];
            MeshFilter filter = gameObject.GetComponent<MeshFilter>();
            MeshRenderer renderer = gameObject.GetComponent<MeshRenderer>();

            if(filter!=null && renderer!=null){
                CombineInstance instance = new CombineInstance();
                instance.mesh = filter.mesh;
                instance.transform = gameObject.transform.localToWorldMatrix;
                instances.Add(instance);

                for (int j = 0; j < renderer.materials.Length; j++) {
                    materials.Add(renderer.materials[j]);
                }
            }
        }

        string guid = AssetDatabase.AssetPathToGUID("Assets");
        string folderName = AssetDatabase.GUIDToAssetPath(guid);
        AssetDatabase.Refresh();

        GameObject merged = new GameObject("merged");
        MeshFilter mergedFilter = merged.AddComponent<MeshFilter>();
        MeshRenderer mergedRenderer = merged.AddComponent<MeshRenderer>();

        Mesh combinedMesh = new Mesh();
        combinedMesh.CombineMeshes(instances.ToArray(), false, true);
        combinedMesh.name = "mergedMesh";
        AssetDatabase.CreateAsset(combinedMesh, folderName+"/mergedMesh.asset");
        mergedFilter.mesh = combinedMesh;

        Material[] combinedMaterials = materials.ToArray();
        for (int i = 0; i < combinedMaterials.Length; i++) {
            Material material = new Material(combinedMaterials[i]);
            AssetDatabase.CreateAsset(material, folderName+"/material"+i+".mat");
        }
        mergedRenderer.materials = combinedMaterials;

        MonoBehaviour.print("Merged prefab and assets saved into: "+ folderName+ "/merged.prefab");
        PrefabUtility.CreatePrefab(folderName+"/merged.prefab", merged);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

    }

   
}
